package cn.hy.tiny.demo.core;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.jboss.C3P0PooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Author huang.xy
 * @Description TODO
 */
public class XMLConfigurationBuilder {


    public Configuration parseConfiguration(InputStream inputStream) throws Exception {
        Configuration configuration = new Configuration();
        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();
        List<Element> elementList = rootElement.selectNodes("//property");
        Properties properties  = new Properties();
        for (Element element : elementList) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setUser(properties.getProperty("user"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element mapperElement : mapperElements) {
            String resourcePath = mapperElement.attributeValue("resource");
            InputStream resourceIn = Resources.getResource(resourcePath);
            xmlMapperBuilder.parseMapperStatement(resourceIn);
        }
        return configuration;
    }


}
